package com.lxq.LeetCode.reverseWords;

import java.util.Stack;

public class Solution {
    public static void main(String[] args) {
        System.out.println(reverseWords2("Let's take LeetCode contest"));
    }

    //法二
    public static String reverseWords2(String s) {
        StringBuffer sb = new StringBuffer();
        StringBuffer res = new StringBuffer();

        for (int i = s.length() - 1; i > -1; i--) {
            if (s.charAt(i) == ' ') {
                res.insert(0, sb.append(' ').toString());
                sb.delete(0, sb.length());
            } else {
                sb.append(s.charAt(i));
            }
        }
        res.insert(0, sb.append(' ').toString());
        return res.deleteCharAt(res.length() - 1).toString();
    }

    //法一
    public static String reverseWords(String s) {
        StringBuffer sb = new StringBuffer();
        Stack<Character> stack = new Stack<>();

        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ' ') {
                while (!stack.isEmpty()) {
                    sb.append(stack.pop());
                }
                sb.append(' ');
            } else {
                stack.push(s.charAt(i));
            }
        }
        while (!stack.isEmpty()) {
            sb.append(stack.pop());
        }
        return sb.toString();
    }

}
